package com.ysxsoft.wdg.ui.fragment;

import android.content.Intent;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ali.auth.third.ui.webview.BaseWebViewActivity;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.classic.common.MultipleStatusView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.home.TbkAdapter;
import com.ysxsoft.wdg.base.BaseFragment;
import com.ysxsoft.wdg.base.BaseGWebViewActivity;
import com.ysxsoft.wdg.bean.BannerBean;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.home.HomeBannerBean;
import com.ysxsoft.wdg.bean.response.CouponListResponse;
import com.ysxsoft.wdg.bean.response.HomeProductResponse;
import com.ysxsoft.wdg.bean.response.PinOrderResponse;
import com.ysxsoft.wdg.bean.response.TopAdResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.ui.activity.center_st.StShopDetailActivity;
import com.ysxsoft.wdg.ui.activity.center_zy.ClassifyActivity;
import com.ysxsoft.wdg.ui.activity.center_zy.GoodsDetailActivity;
import com.ysxsoft.wdg.ui.activity.home.JDListActivity;
import com.ysxsoft.wdg.ui.activity.home.LocationActivity;
import com.ysxsoft.wdg.ui.activity.home.MessageActivity;
import com.ysxsoft.wdg.ui.activity.home.NewActivity;
import com.ysxsoft.wdg.ui.activity.home.ShareInviteActivity;
import com.ysxsoft.wdg.ui.activity.home.TbJxActivity;
import com.ysxsoft.wdg.ui.activity.home.TbSearchActivity;
import com.ysxsoft.wdg.ui.activity.login.LoginValid;
import com.ysxsoft.wdg.ui.activity.my.MyKfActivity;
import com.ysxsoft.wdg.util.AlibcUtils;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.banner.BannerImageLoader;
import com.ysxsoft.wdg.util.delayaction.Action;
import com.ysxsoft.wdg.util.delayaction.SingleCall;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.util.transform.FastSpeedLinearLayoutManager;
import com.ysxsoft.wdg.util.zxing.ScanActivity;
import com.ysxsoft.wdg.wxapi.TipView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

public class HomeFragment extends BaseFragment {

    public interface OnHomeChangeListener {
        void toCenter();

        void toTeHui();
    }

    private OnHomeChangeListener onHomeChangeListener;

    public void setOnHomeChangeListener(OnHomeChangeListener onHomeChangeListener) {
        this.onHomeChangeListener = onHomeChangeListener;
    }

    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.title_sao)
    ImageView title_sao;
    @BindView(R.id.iv0)
    ImageView iv0;
    @BindView(R.id.tv0)
    TextView tv0;
    @BindView(R.id.iv1)
    ImageView iv1;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.iv2)
    ImageView iv2;
    @BindView(R.id.tv2)
    TextView tv2;
    @BindView(R.id.iv3)
    ImageView iv3;
    @BindView(R.id.tv3)
    TextView tv3;
    @BindView(R.id.iv4)
    ImageView iv4;
    @BindView(R.id.tv4)
    TextView tv4;
    @BindView(R.id.iv5)
    ImageView iv5;
    @BindView(R.id.tv5)
    TextView tv5;
    @BindView(R.id.iv6)
    ImageView iv6;
    @BindView(R.id.tv6)
    TextView tv6;
    @BindView(R.id.iv7)
    ImageView iv7;
    @BindView(R.id.tv7)
    TextView tv7;
    @BindView(R.id.tip)
    TipView tip;
    @BindView(R.id.ll_tip)
    LinearLayout llTip;
    @BindView(R.id.iv_ms)
    ImageView ivXs;
    @BindView(R.id.iv_new)
    ImageView ivNew;
    @BindView(R.id.iv_find)
    ImageView ivFind;
    @BindView(R.id.iv_gg)
    ImageView ivGg;
    @BindView(R.id.c)
    TextView c;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;
    @BindView(R.id.multStatusView2)
    MultipleStatusView multStatusView2;
    private String id1, id2, id3, content4;
    private String categoryId="";
    public static final int HOME_REQUEST_CODE_SCAN = 0x05;

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    private TbkAdapter adapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fm_one;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        //设置图片加载器
        banner.setImageLoader(new BannerImageLoader());

        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setFocusable(false);
        recyclerview.setLayoutManager(new FastSpeedLinearLayoutManager(getContext()));

        adapter = new TbkAdapter(R.layout.item_tbk);
        recyclerview.setAdapter(adapter);
        multStatusView.showLoading();


        tv0.setText("我的淘宝");
        iv0.setImageResource(R.mipmap.tb);
        tv7.setText("客服");
        iv7.setImageResource(R.mipmap.home1);

        initRefresh();
        getBanner();
        getList();

        getTopAd();
        getBottomAd();
    }

    @Override
    public void onResume() {
        super.onResume();
        c.setText(SharePrefUtils.getAddress());

    }

    private void initRefresh() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                getList();

                getTopAd();
                getBottomAd();
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page++;
                getList();
            }
        });
    }

    private void getBanner() {
        mApiHelper.getHomeBanner(new Observer<BaseBean<HomeBannerBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<HomeBannerBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    HomeBannerBean data = baseBean.getData();
                    List<BannerBean> bannerList = data.getBanner();
                    List<String> bannerList2 = new ArrayList<>();
                    for (int i = 0; i < bannerList.size(); i++) {
                        bannerList2.add(bannerList.get(i).getPic());
                    }

                    banner.setImages(bannerList2);
                    banner.start();

                    List<BannerBean> newsList = data.getNews();
                    List<String> tipList2 = new ArrayList<>();
                    for (int i = 0; i < newsList.size(); i++) {
                        tipList2.add(newsList.get(i).getTitle());
                    }
                    tip.setTipList(tipList2);

                }
            }

            @Override
            public void onError(Throwable e) {
                multStatusView.showError();
            }

            @Override
            public void onComplete() {
                multStatusView.showContent();
            }
        });
    }

    @Override
    protected void setListener() {
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SingleCall.getInstance().addAction(new Action() {
                    @Override
                    public void call() {
                        HomeProductResponse.DataBean item = (HomeProductResponse.DataBean) adapter.getItem(position);
                        AlibcUtils.showDetail(getContext(), item.getNum_iid(), SharePrefUtils.getUserId());
                    }
                }).addValid(new LoginValid(mContext, 1)).doCall();
            }
        });
    }

    @OnClick({R.id.title_location, R.id.title_msg, R.id.title_sao,
            R.id.title_content, R.id.ll0, R.id.ll1, R.id.ll2, R.id.ll3,
            R.id.ll4, R.id.ll5, R.id.ll6, R.id.ll7, R.id.ll_tip, R.id.iv_ms,
            R.id.iv_new, R.id.iv_find, R.id.iv_gg, R.id.tv_hot,R.id.c})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.c:
            case R.id.title_location://定位
                startActivity(new Intent(mContext, LocationActivity.class));
                break;
            case R.id.title_msg://消息
                MessageActivity.start(mContext);
                break;
            case R.id.title_sao://扫码
                Intent scanIntent = new Intent(getActivity(), ScanActivity.class);
                startActivityForResult(scanIntent, HOME_REQUEST_CODE_SCAN);
                break;
            case R.id.title_content://搜索
                startActivity(new Intent(mContext, TbSearchActivity.class));
                break;
            case R.id.ll0://我的淘宝
                TbJxActivity.start(mContext);
                break;
            case R.id.ll1://分享邀请
                SingleCall.getInstance().addAction(new Action() {
                    @Override
                    public void call() {
                        startActivity(new Intent(mContext, ShareInviteActivity.class));
                    }
                }).addValid(new LoginValid(mContext, 1)).doCall();
                break;
            case R.id.ll2://新手指南
                startActivity(new Intent(mContext, NewActivity.class));
                break;
            case R.id.ll3://同城服务
                onHomeChangeListener.toCenter();
                break;
            case R.id.ll4://特惠区
                onHomeChangeListener.toTeHui();
                break;
            case R.id.ll5://京东
                //跳转至京东
                Intent jdIntent=new Intent(getActivity(),JDListActivity.class);
                startActivity(jdIntent);
                break;
            case R.id.ll6://九尊法务
                ToastUtils.showToast("敬请期待");
                break;
            case R.id.ll7://九尊公益 改为了我的客服
                MyKfActivity.start(mContext);
                break;
            case R.id.ll_tip://淘宝客头条
                break;
            case R.id.iv_ms://限时秒杀
                GoodsDetailActivity.start(getActivity(), id1);
                break;
            case R.id.iv_new://新品好货
                GoodsDetailActivity.start(getActivity(), id2);
                break;
            case R.id.iv_find://发现好货
                GoodsDetailActivity.start(getActivity(), id3);
                break;
            case R.id.iv_gg://广告
//                BaseGWebViewActivity.start(getActivity(), "广告", content4);
//                ClassifyActivity.start(mContext);
                Intent intent=new Intent(getActivity(),ClassifyActivity.class);
                intent.putExtra("categoryId",categoryId);
                startActivity(intent);
                break;
            case R.id.tv_hot://购物精选
                TbJxActivity.start(mContext);
                break;
        }
    }

    private int page = 1;

    /**
     * 获取精选
     */
    private void getList() {
        OkHttpUtils.post()
                .url(UrlHost.HOME_PRODUCT)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("page", page + "")
                .addParams("type", 0 + "")//	综合0，销量1，最新2，到手价倒序3，到手价正序4
                .addParams("keyword", "全部")
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    multStatusView2.showError();
                    reset();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                reset();
                if (response != null) {
                    HomeProductResponse homeProductResponse = JsonUtils.parseByGson(response, HomeProductResponse.class);
                    if (homeProductResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(homeProductResponse.getCode())) {
                        List<HomeProductResponse.DataBean> list = homeProductResponse.getData();
                        if (page == 1) {
                            multStatusView2.showContent();
                            if (list != null && !list.isEmpty()) {
                            } else {
                                multStatusView2.showEmpty();
                            }
                            adapter.setNewData(list);
                        } else {
                            adapter.addData(list);
                        }
                    }
                } else {
                    multStatusView2.showError();
                }
            }
        });
    }

    private void reset() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh(true);
        }
        refreshLayout.finishLoadmore();
    }

    /**
     * 获取顶部广告
     */
    private void getTopAd() {
        OkHttpUtils.post()
                .url(UrlHost.MAIN_AD)
                .addParams("type", "0")//0：上边3个是   1：下边1个
                .addParams("style", "1")    //1首页3自营2实体
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    TopAdResponse messageBean = JsonUtils.parseByGson(response, TopAdResponse.class);
                    if (messageBean == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(messageBean.getCode())) {
                        List<TopAdResponse.DataBean> list = messageBean.getData();
                        if (list.size() == 3) {
                            Glide.with(getActivity()).load(list.get(0).getPic()).into(ivXs);
                            Glide.with(getActivity()).load(list.get(1).getPic()).into(ivNew);
                            Glide.with(getActivity()).load(list.get(2).getPic()).into(ivFind);
                            id1 = "" + list.get(0).getGoodsid();
                            id2 = "" + list.get(1).getGoodsid();
                            id3 = "" + list.get(2).getGoodsid();
                        }
                    }
                } else {
                }
            }
        });
    }

    /**
     * 获取顶部广告
     */
    private void getBottomAd() {
        OkHttpUtils.post()
                .url(UrlHost.MAIN_AD)
                .addParams("type", "1")//0：上边3个是   1：下边1个
                .addParams("style", "1")    //1首页3自营2实体
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    TopAdResponse messageBean = JsonUtils.parseByGson(response, TopAdResponse.class);
                    if (messageBean == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(messageBean.getCode())) {
                        List<TopAdResponse.DataBean> list = messageBean.getData();
                        if (list.size() == 1) {
                            Glide.with(getActivity()).load(list.get(0).getPic()).into(ivGg);
                            categoryId=list.get(0).getGoodsid()+"";
                            content4 = list.get(0).getContent();
                        }
                    }
                } else {
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case HOME_REQUEST_CODE_SCAN:
                //扫码结果
                try {
                    if (data != null) {
                        String result = data.getStringExtra("result");
                        if (result != null) {
                            StShopDetailActivity.start(getActivity(),result);
                        }else{
                            ToastUtils.showToast("未扫到任何二维码！");
                        }
                    } else {
                        ToastUtils.showToast("二维码识别失败！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}
